<template>
  <div>
    <div class="base-container">
      <div class="title-box">
        <p class="title">对账差异数据总览</p>
        <el-tree-select
          v-model="companyId"
          :data="companyList"
          :render-after-expand="true"
          :props="treeProps"
          node-key="id"
          placeholder="请选择公司"
          clearable 
          check-strictly
          multiple
          show-checkbox
          collapse-tags
          style="width: 320px;"
          @clear="handleCompanyChange"
          @remove-tag="handleCompanyChange"
          @visible-change="handleCompanyMultiSelect"
        />
      </div>
      <div class="top-card">
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ formatNumberWithCommas(total.total_fee.toFixed(2)) }}</p>
          <p class="label">当前对账差异总金额（元）</p>
        </div>
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ formatNumberWithCommas(Math.floor(total.total_order)) }}</p>
          <p class="label">当前对账差异总笔数</p>
        </div>
        <div class="top-card-box">
          <p class="num" id="totalUser">{{ formatNumberWithCommas(total.yesterdayNobillPriceNum.toFixed(2)) }}</p>
          <p class="label">近三日对账差异金额（元）</p>
        </div>
        <div class="top-card-box last-card">
          <p class="num" id="totalOrder">{{ formatNumberWithCommas(Math.floor(total.yesterdayNobillOrderNum)) }}</p>
          <p class="label">近三日对账差异笔数</p>
        </div>
      </div>
    </div>

    <div class="base-container mt-10px">
      <div class="title-box">
        <p class="title">对账差异图</p>
      </div>
      <div class="flex flex-between mt-20px">
        <el-radio-group v-model="chartInfo.orderBillType" class="ml-10px" @change="getChartData">
          <el-radio-button value="3">对账差异金额</el-radio-button>
          <el-radio-button value="4">对账差异笔数</el-radio-button>
        </el-radio-group>
        <div class="flex items-center">
          <el-select 
            multiple clearable collapse-tags
            v-model="chartInfo.channelCode" 
            placeholder="请选择渠道" 
            style="width: 400px"
            :multiple-limit="10"
            @clear="handleDateChange"
             @remove-tag="handleDateChange"
            @visible-change="handleMultiSelect">
            <el-option
              v-for="dict in channelList"
              :key="dict.channelCode"
              :label="dict.channelName"
              :value="dict.channelCode"
            />
          </el-select>
          <el-date-picker 
            class="ml-10px"
            v-model="chartInfo.searchDate"
            :clearable="false"
            type="daterange"
            value-format="YYYYMMDD"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 240px"
            :disabled-date="handleDisabledDate"
            @change="handleDateChange"
            @calendar-change="chooseDay = $event[0]"
            @focus="chooseDay = null">
          </el-date-picker>
        </div>
      </div>
      <div class="chart" id="chart"></div>

      <div class="title-box mt-20px">
        <p class="title">对账差异表</p>
      </div>
      <el-table class="mt-20px" border v-loading="tableInfo.loading" :data="tableInfo.list">
        <el-table-column label="日期" align="center" prop="time" />
        <el-table-column label="公司" align="center" prop="companyName" />
        <el-table-column label="来源渠道" align="center" prop="channelName" />
        <el-table-column label="线路" align="center" prop="line_id" />
        <el-table-column label="车辆" align="center" prop="plate_num" />
        <el-table-column label="对账差异金额（元）" align="center" prop="orderNobillPrice">
          <template #default="scope">
            <span>{{ formatNumberWithCommas(formatAmount(scope.row.orderNobillPrice)) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="对账差异笔数" align="center" prop="orderNobillNum">
          <template #default="scope">
            <span>{{ formatNumberWithCommas(scope.row.orderNobillNum) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <pagination
      v-show="tableInfo.total>0"
      :total="tableInfo.total"
      v-model:page="tableInfo.pageNum"
      v-model:limit="tableInfo.pageSize"
      @pagination="getTableList"
    /> -->
  </div>
</template>

<script setup name="Differentbill">
import { nextTick, reactive } from 'vue'
import { useTransition, TransitionPresets } from '@vueuse/core'
import { 
  getTotalDataApi,
  getChartDataApi,
  getListDataApi
} from "@/api/statistic/differentbill"
import { listChannel } from "@/api/channel/platchannelinfo"
import { getAllCompanies } from '@/api/company/company'

// import gsap from 'gsap'
import * as echarts from 'echarts'
import { chart_bar } from '@/utils/echarts'
import { deepClone } from '@/utils/index'
import Big from 'big.js'

const router = useRouter()
const { proxy } = getCurrentInstance()

const companyId = ref([])
const channelList = ref([])
const companyList = ref([])
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.check == false
  }
}

const duration = 1500
const total = ref({
  total_fee: 0,
  total_order: 0,
  yesterdayNobillPriceNum: 0,
  yesterdayNobillOrderNum: 0
})
const totalRes = ref({})
const chartInfo = ref({
  searchDate: [],
  channelCode: [],
  orderBillType: '3',    // 3差异金额  4差异笔数
})
const tableInfo = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
  loading: false,
  list: []
})
const chooseDay = ref()

onMounted(() => {
  let date = new Date()
  date.setDate(date.getDate() - 8)
  let yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  chartInfo.value.searchDate = [proxy.parseTime(date, '{y}{m}{d}'), proxy.parseTime(yesterday, '{y}{m}{d}')]
  getChannelList()
  getCompanyList()
  getTotalData()
  getTableList()
})

const handleMultiSelect = (val) => {
  if (!val) {
    getChartData()
    getTableList()
  }
}

const handleCompanyMultiSelect = (val) => {
  if (!val) {
    handleCompanyChange()
  }
}

const handleCompanyChange = () => {
  getTotalData()
  getChartData()
  getTableList()
}

const handleDateChange = () => {
  getChartData()
  getTableList()
}

const handleDisabledDate = (date) => {
  const selectDate = proxy.parseTime(date, '{y}-{m}-{d}')
  const currentDate = proxy.parseTime(new Date(), '{y}-{m}-{d}')
  if (chooseDay.value) {
    const one = 30 * 24 * 3600 * 1000
    const minDate = chooseDay.value - one
    const maxDate = chooseDay.value - 0 + one // 当前日期 + one = 7天之后(必须-0，不然不会变成数字时间戳格式)
    return date.getTime() < minDate || date.getTime() > maxDate || selectDate >= currentDate
  } else {
    return selectDate >= currentDate
  }
}

// 对账差异表
const getTableList = () => {
  tableInfo.value.loading = false
  const params = {
    beginDate: chartInfo.value.searchDate[0],
    endDate: chartInfo.value.searchDate[1],
    channelCodes: chartInfo.value.channelCode.join(','),
    companyIds: companyId.value.join(',')
  }
  getListDataApi(params).then(res => {
    tableInfo.value.list = res.data
    tableInfo.value.loading = false
  })
}

// 渠道列表
const getChannelList = () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
  }
  listChannel(params).then(response => {
    channelList.value = response.rows
    getChartData()
  })
}

// 公司列表
const getCompanyList = () => {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

// 获取累计数据
const getTotalData = () => {
  const params = {
    companyIds: companyId.value.join(',')
  }
  getTotalDataApi(params).then(res => {
    totalRes.value = res.data
    setTotalAnimation()
  })
}

// 图表数据
const getChartData = () => {
  const params = {
    beginDate: chartInfo.value.searchDate[0],
    endDate: chartInfo.value.searchDate[1],
    orderBillType: chartInfo.value.orderBillType,
    channelCodes: chartInfo.value.channelCode.join(','),
    companyIds: companyId.value.join(',')
  }
  getChartDataApi(params).then(response => {
    setChart(response.data)
  })
}

// 设置图表
const setChart = (res) => {
  const keys = Object.keys(res)
  let legend = []
  let xData = []
  let series = []
  for (let i = 0; i < keys.length; i++) {
    const code = keys[i]
    const channel = channelList.value.find(obj => {
      return obj.channelCode == code
    })
    if (channel) {
      legend.push(channel.channelName)
    }
    const dataArr = res[code]
    let yArr = []
    dataArr.forEach(item => {
      if (i === 0) {
        xData.push(item.ref_date)
      }
      if (chartInfo.value.orderBillType == 3) {
        yArr.push(proxy.formatAmount(item.num))
      } else {
        yArr.push(item.num)
      }
    })
    let info = {
      name: channel ? channel.channelName : '',
      type: 'bar',
      stack: 'total',
      label: {
        show: true,
        color: '#ffffff',
        formatter(params) {
          return params.value == 0 ? '' : params.value
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: yArr
    }
    series.push(info)
  }
  const dom = document.getElementById('chart')
  if (echarts.getInstanceByDom(dom)) {
    echarts.dispose(dom)
  }
  const chart = echarts.init(dom)
  let options = deepClone(chart_bar)
  options.xAxis.data = xData
  options.series = series
  options.legend.data = legend
  if (chartInfo.value.orderBillType == 3) {
    options.toolbox.feature.saveAsImage.name = '对账差异金额'
  } else {
    options.toolbox.feature.saveAsImage.name = '对账差异笔数'
  }
  chart.setOption(options, true)
}

// 统计数字滚动动画
const setTotalAnimation = () => {
  const totalFee = ref(total.value.total_fee)
  total.value.total_fee = useTransition(totalFee, {
    duration: duration,
    // transition: TransitionPresets.easeInOutCubic
  })
  totalFee.value = Number(proxy.formatAmount(totalRes.value.total_fee))

  const totalOrder = ref(total.value.total_order)
  total.value.total_order = useTransition(totalOrder, {
    duration: duration
  })
  totalOrder.value = Number(totalRes.value.total_order)

  const yesterdayNobillPriceNum = ref(total.value.yesterdayNobillPriceNum)
  total.value.yesterdayNobillPriceNum = useTransition(yesterdayNobillPriceNum, {
    duration: duration
  })
  yesterdayNobillPriceNum.value = Number(proxy.formatAmount(totalRes.value.yesterdayNobillPriceNum))

  const yesterdayNobillOrderNum = ref(total.value.yesterdayNobillOrderNum)
  total.value.yesterdayNobillOrderNum = useTransition(yesterdayNobillOrderNum, {
    duration: duration
  })
  yesterdayNobillOrderNum.value = Number(totalRes.value.yesterdayNobillOrderNum)
}


</script>

<style scoped lang="scss">
@import '../../../assets/styles/statistic.scss';
</style>

